package be.ad.coffeebreak.web;

import be.ad.coffeebreak.domain.User;
import be.ad.coffeebreak.services.UsersService;

import javax.ejb.EJB;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.Principal;

/**
 * @author Stefan Bangels
 */
public final class AuthenticationFilter implements Filter {

    @EJB
    protected UsersService usersService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {
        User user = null;
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpSession session = httpServletRequest.getSession(true);
        if (session != null) {
            user = (User) session.getAttribute(WebConstants.ATTRIBUTE_USER);
            if (user == null) {
                Principal principal = httpServletRequest.getUserPrincipal();
                if (principal != null) {
                    String email = principal.getName();
//                    user = usersService.findUserByEmail(email);
                    user = new User();
                    user.setId(1L);
                    user.setEmail(email);
                    user.setName("Stefan Bangels");
                }
            }
        }
        if (user != null) {
            request.setAttribute(WebConstants.ATTRIBUTE_USER, user);
            filterChain.doFilter(request, response);
        } else {
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "not logged in yet");
        }
    }

    @Override
    public void destroy() {
    }

}
